package com.chezai.client.activitys;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.chezai.client.R;
import com.chezai.client.bean.TerminalBaseInfo;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.utils.PreferenceManager;
import com.jx.driving.request.Terminal0x0003Request;
import com.jx.driving.request.Terminal0x0100Request;
import com.jx.driving.response.AbstractResponse;
import com.jx.driving.response.Terminal0x8100Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 终端注册注销页
 * Created by likunyang on 2017/9/12.
 */

public class TerminalInfoActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.btn_back)
    Button btnBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_maker_company)
    TextView tvMakerCompany;
    @BindView(R.id.tv_region)
    TextView tvRegion;
    @BindView(R.id.tv_sn)
    TextView tvSn;
    @BindView(R.id.tv_sim)
    TextView tvSim;
    @BindView(R.id.tv_imei)
    TextView tvImei;
    @BindView(R.id.tv_car_info)
    TextView tvCarInfo;
    @BindView(R.id.cb_terminal_register)
    CheckBox cbTerminalRegister;

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_status;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        cbTerminalRegister.setVisibility(View.VISIBLE);
        boolean isRegister = PreferenceManager.isRegister();
        cbTerminalRegister.setChecked(isRegister);
        cbTerminalRegister.setText(isRegister ? "终端注销" : "终端注册");

        TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
        if (terminalBaseInfo != null) {
            tvMakerCompany.setText(TerminalApplication.channelModel + "制造商" + "  型号 " + TerminalApplication.channelModel);
            tvRegion.setText(terminalBaseInfo.getProvinceId() + "" + terminalBaseInfo.getCityId());
            tvSn.setText(terminalBaseInfo.getDevice());
            tvSim.setText(Long.valueOf(terminalBaseInfo.getSim()) + "");
            tvImei.setText(DeviceFactory.getInstance().getHardware().getImei(this));
            int signColor = terminalBaseInfo.getSignColor();
            tvCarInfo.setText(terminalBaseInfo.getIdentification() + " " +
                    (signColor == 1 ? "蓝色" :
                            signColor == 2 ? "黄色" :
                                    signColor == 3 ? "黑色" :
                                            signColor == 4 ? "白色" :
                                                    signColor == 9 ? "其他" : ""));
        }
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        super.setListener();
        cbTerminalRegister.setOnCheckedChangeListener(this);
    }

    @OnClick(R.id.btn_back)
    public void onClick() {
        finish();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //终端注册
        if (isChecked) {
            TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
            if (terminalBaseInfo != null) {
                final Terminal0x0100Request obj = new Terminal0x0100Request();
                obj.setCityId(terminalBaseInfo.getCityId());
                obj.setProvinceId(terminalBaseInfo.getProvinceId());
                obj.setManufactureId(TerminalApplication.channelModel);
                obj.setDeviceModel(TerminalApplication.channelModel);
                obj.setDeviceSequence(DeviceFactory.hardware.getSerialNumber(this));
                obj.setImei(DeviceFactory.getInstance().getHardware().getImei(this));
                obj.setSignColor((short) terminalBaseInfo.getSignColor());
                obj.setIdentification(terminalBaseInfo.getIdentification());
                TerminalSocketClientManager.getInstance().tell(obj, false);
            } else {
                showToast("终端信息不完整，尝试重启应用");
            }
        } else {
            //终端注销
            Terminal0x0003Request rsp = new Terminal0x0003Request();
            TerminalSocketClientManager.getInstance().tell(rsp, false);
        }
    }

    /**
     * 通用应答 此处为终端注销应答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventAbstractResponse(AbstractResponse abstractResponse) {
        Logger.t("AbstractResponse").i(abstractResponse.toString());
        int msgId = abstractResponse.getId();
        switch (msgId) {
            //终端注销
            case 0x0003:
                if (0 == abstractResponse.getResult()) {
                    //注销成功
                    cbTerminalRegister.setChecked(false);
                    cbTerminalRegister.setText("终端注册");
                    PreferenceManager.putBoolean(Const.SP_IS_TERMINAL_REGISTER, false);
                    showToast("终端注销成功");
                } else {
                    //注销失败
                    showToast("注销失败");
                }
                break;
        }
    }

    /**
     * 终端注册应答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8100Response(Terminal0x8100Response ox8100) {
        Logger.t("0x8100终端注册").w(ox8100.toString());
        //0：成功；1：车辆已被注册；2：数据库中无该车辆；3：终端已被注册；4：数据库中无该终端。
        switch (ox8100.getResult()) {
            case 0:
                cbTerminalRegister.setChecked(true);
                cbTerminalRegister.setText("终端注销");
                showToast("终端注册成功");
                //保存注册状态
                PreferenceManager.putBoolean(Const.SP_IS_TERMINAL_REGISTER, true);
                //保存设备信息
                TerminalBaseInfoDaoManager.getInstance().insertAndUpdateTerminalBaseInfo(ox8100);
                //开始鉴权
                TerminalSocketClientManager.getInstance().authenTicate();
                break;
            case 1:
                showToast("车辆已被注册");
                break;
            case 2:
                showToast("数据库中无该车辆");
                break;
            case 3:
                showToast("终端已被注册");
                break;
            case 4:
                showToast("数据库中无该终端");
                break;
        }
    }
}
